/**
 * 新增客户反馈接口
 */

//引入Q模块
let Q = require('q');
//引入公共函数
let util = require('../../util');

let redis;

let index = function(getData, postData, config, _redis, db) {
	let deferred = Q.defer();
	if(postData.feedBackType && postData.feedBackContent && postData.feedBackContact) {
		redis = _redis;
		let userId;
		getUserId(postData._3rdSession).then(function(_userId) {
			userId = _userId;
			return db.connectDB('common');
		}).then(function(commonDB) {
			return commonDB.insert('feedBacks', {
				feedBackUserId: userId,
				feedBackType: postData.feedBackType,
				feedBackContent: postData.feedBackContent,
				feedBackContact: postData.feedBackContact,
				feedBackTimestamp: Date.now()
			});
		}, function() {
			//连接公共数据库失败
			deferred.reject('-0044');
		}).then(function() {
			deferred.resolve(1);
		}, function() {
			//新增客户反馈失败
			deferred.reject('-0214');
		});
	}
	else {
		//新增客户反馈接口参数不足
		deferred.reject('-0213');
	}
	return deferred.promise;
}

let getUserId = function(_3rdSession) {
	let deferred = Q.defer();
	redis.get(_3rdSession).then(function(data) {
		if(data) {
			data = JSON.parse(data);
			if(data.openId) {
				deferred.resolve(data.openId);
			}
			else {
				deferred.reject();
			}
		}
		else {
			deferred.reject();
		}
	}, function(err) {
		console.log(err);
		deferred.reject();
	});
	return deferred.promise;
}

module.exports = {
	index: index
}